from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import time
import traceback
import uvicorn
from db.mysql import mysql
from db.mongo import mongo 
from contextlib import asynccontextmanager
from core.logging import setup_logging, log_error
from middleware.logging_middleware import log_middleware
from fastapi.middleware.cors import CORSMiddleware
from core.config import settings
# 初始化日志系统
setup_logging()

@asynccontextmanager
async def lifespan(app: FastAPI):
    await mysql.connect()
    await mongo.connect()
    yield
    await mysql.close()
    await mongo.close()

app = FastAPI(lifespan=lifespan,  title="自动应答Agent AI API", description="自动应答Agent AI API", version="1.0.0")
# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 添加中间件
app.middleware("http")(log_middleware)

# 导入路由（保持不变）
from api.routes import content, agent, image, chat, industry, company
app.include_router(content.router)
app.include_router(agent.router)
app.include_router(image.router)
app.include_router(chat.router)
app.include_router(industry.router)
app.include_router(company.router)

@app.get("/")
async def root():
    """
    根路径，返回API信息
    """
 
    return {"message": "欢迎使用自动应答Agent AI API"}

@app.get("/health")
async def health_check():
    """
    健康检查接口（新增数据库连接检查）
    """
    mysql_connected = await mysql.check_connection()
    mongo_connected = await mongo.check_connection()
    status = "healthy" if mysql_connected and mongo_connected else "unhealthy"
    
    return {
        "status": status,
        "services": {
            "mysql": "connected" if mysql_connected else "disconnected",
            "mongo": "connected" if mongo_connected else "disconnected"
        }
    }

# 获取等待时间
@app.get("/getInterval")
async def get_interval():
    """
    获取等待时间
    """
    # interval = settings.MYSQL_HOST
    return {
        "code": 200,
        "message": "查询成功",
        "interval": settings.INTERVAL
    }

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8005, log_level="info", reload=True)